package com.shjy.driver.amap;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.shjy.driver.activity.LoginActivity;
import com.shjy.driver.activity.MainActivity;
import com.shjy.driver.service.LocationService;
import com.shjy.driver.util.AppUtil;
import com.shjy.driver.util.Const;

import java.io.File;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Created by ld on 2017/6/28.
 */

public class LocationUtil {

    private static final String TAG = "LocationUtil";
    private static AMapLocationClient mLocationClient = null;
    private static int flag = 0;
    protected static Context mContext;

    public static void location(final Context context) {
        android.os.Handler handler=new android.os.Handler(context.getMainLooper());
        try {
            mContext = context;
            netThread.start();
            flag = 0;
            Logger logger = Logger.getLogger(TAG);
            // 声明AMapLocationClient类对象
            Runnable runnable=new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    //要做的事情
                    if(flag==0){
                        try {
                            String text = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " need to do";
                            initData(text);

                            SharedPreferences sharedPreferences = context.getSharedPreferences("cookie", Context.MODE_MULTI_PROCESS);
                            final String driverUuid = sharedPreferences.getString(Const.KEY_TOKEN, "");

                            SharedPreferences sharedPreferencesbillid = context.getSharedPreferences("cookie", Context.MODE_MULTI_PROCESS);
                            final String waybillId = sharedPreferencesbillid.getString(Const.waybillId, "");
                            final String latLatest = getStringAttrMul(context,"latLatest");
                            final String lonLatest = getStringAttrMul(context,"lonLatest");

                            String lastUploadTime = getStringAttrMul(context,"lastUploadTime");
                            boolean gpsFlag = true;
                            if(lastUploadTime!=null && !"".equals(lastUploadTime)){
                                try{
                                    if( new Date().getTime() - Long.parseLong(lastUploadTime) < 4300 ){
                                        gpsFlag = false;
                                    }
                                }catch (Exception ex){
                                    try{
                                        initData("444error occures in line 281="+ex.getMessage()+ " \n");
                                    }catch (Exception e){
                                        ex.printStackTrace();
                                    }
                                    ex.printStackTrace();
                                }
                            }

                            if (!TextUtils.isEmpty(driverUuid) && gpsFlag && !TextUtils.isEmpty(waybillId) && !"undefined".equals(waybillId)) {
                                saveStringAttrMul(context,"lastUploadTime",String.valueOf(new Date().getTime()));

                                String url = Const.DOMAIN + "driverPosition/addDriveLowSpeedPosition.htm";
                                RequestQueue requestQueue = Volley.newRequestQueue(context);

                                StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                                    @Override
                                    public void onResponse(String s) {
                                        try{
                                            initData("insert wait time="+s+ " \n");
                                        }catch (Exception ex){
                                            ex.printStackTrace();
                                        }
                                        Log.d(TAG, "onResponse " + s);
                                    }
                                }, new Response.ErrorListener() {
                                    @Override
                                    public void onErrorResponse(VolleyError volleyError) {
                                        Log.d(TAG, "onErrorResponse " + volleyError.getMessage());
                                    }
                                }) {
                                    @Override
                                    protected Map<String, String> getParams() throws AuthFailureError {
                                        Map<String, String> map = new HashMap<String, String>();
                                        map.put("token", driverUuid);
                                        map.put("lon", lonLatest);
                                        map.put("lat", latLatest);
                                        map.put("waybillId", waybillId);
                                        Log.d(TAG, "getParams " + map);
                                        return map;
                                    }
                                };

                                requestQueue.add(stringRequest);
                            }
                        } catch (Exception e) {
                            try{
                                initData("000error occures in line 63="+e.getMessage()+ " \n");
                            }catch (Exception ex){
                                ex.printStackTrace();
                            }
                        }
                    }
                }
            };
            // 声明定位回调监听器
            AMapLocationListener mLocationListener = new AMapLocationListener() {
                @Override
                public void onLocationChanged(AMapLocation amapLocation) {
                    if (amapLocation != null) {
                        if (amapLocation.getErrorCode() == 0) {
                            flag = 1;
                            //Logger logger = Logger.getLogger(TAG);
                            //logger.info("updateLocation is wifi="+amapLocation.getLatitude()+","+amapLocation.getLongitude());
                            // 上传定位信息
                            //updateLocation(amapLocation, context);
                            String message = "gps speed="+amapLocation.getSpeed()+ " ==getAccuracy="+amapLocation.getAccuracy()
                                    + " ==getGpsAccuracyStatus="+amapLocation.getGpsAccuracyStatus()+ " ==getSatellites="+amapLocation.getSatellites()
                                    + " ==getProvider="+amapLocation.getProvider()+ " ==getBearing="+amapLocation.getBearing()+ " ==getLocationType="+amapLocation.getLocationType();
                            Double longitude = amapLocation.getLongitude();//获取经度
                            Double latitude = amapLocation.getLatitude();//获取纬度
                            String longitudestr = String.valueOf(longitude);
                            String latitudestr = String.valueOf(latitude);

                            Message msg = new Message();
                            Bundle data = new Bundle();
                            data.putString("lonCurrent", longitudestr);
                            data.putString("latCurrent", latitudestr);
                            data.putString("accuracy", amapLocation.getAccuracy()+"");
                            data.putString("message", message);
                            msg.setData(data);
                            msg.what = 0x1;
                            netHandler.sendMessage(msg);
//                            try {
//                                mLocationClient.stopLocation();
//                                mLocationClient.onDestroy();//销毁定位客户端，同时销毁本地定位服务。
//                            } catch (Exception ex) {
//                                //logger.info("mLocationClient.stopLocation() error=" + ex.getMessage());
//                            }

                        }
                    }
                }
            };


            // 声明AMapLocationClientOption对象
            AMapLocationClientOption mLocationOption = null;
            // 初始化定位
            mLocationClient = new AMapLocationClient(context);
            // 设置定位回调监听
            mLocationClient.setLocationListener(mLocationListener);
            // 初始化AMapLocationClientOption对象
            mLocationOption = new AMapLocationClientOption();
            //logger.info("updateLocation is wifi="+isWifiConnected(context));

//        if(!isWifiConnected(context))
//        {
//            // 设置定位模式为AMapLocationMode.Device_Sensors，GPS定位模式。首先通过GPS定位，如果获取不到，再通过基站定位
//            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Device_Sensors);
//            // 获取一次定位结果：
//            // 该方法默认为false。
//            mLocationOption.setOnceLocation(false);
//            // 获取最近3s内精度最高的一次定位结果：
//            // 设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
//            mLocationOption.setOnceLocationLatest(false);
//        }else{
//            // 设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
//            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//            mLocationOption.setGpsFirst(true);
//            // 获取一次定位结果：
//            // 该方法默认为false。
//            mLocationOption.setOnceLocation(false);
//            // 获取最近3s内精度最高的一次定位结果：
//            // 设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
//            mLocationOption.setOnceLocationLatest(false);
//        }
            //boolean flag = is4GAvailable(context);
            //设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
            //mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.Transport);
            // 设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
            //mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Device_Sensors);
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //mLocationOption.setGpsFirst(true);
            mLocationOption.setWifiScan(true);
            // 获取一次定位结果：
            // 该方法默认为false。
            //mLocationOption.setOnceLocation(true);
            // 获取最近3s内精度最高的一次定位结果：
            // 设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
            //mLocationOption.setOnceLocationLatest(true);

            // 设置定位间隔,单位毫秒,默认为2000ms，最低1000ms。
            mLocationOption.setInterval(5000);

            //传入true，启动定位，AmapLocationClient会驱动设备扫描周边wifi，获取最新的wifi列表（相比设备被动刷新会多消耗一些电量），从而获取更精准的定位结果。
            //mLocationOption.setWifiActiveScan(true);
            // 设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(false);
            // 单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
            mLocationOption.setHttpTimeOut(10000);
            // 关闭缓存机制
            mLocationOption.setLocationCacheEnable(false);
            // 给定位客户端对象设置定位参数
            mLocationClient.setLocationOption(mLocationOption);
            // 启动定位
            mLocationClient.startLocation();
            try {
                handler.postDelayed(runnable, 4000);//每四秒执行一次runnable.
            }catch (Exception ex){
                try{
                    initData("0011error occures in line 155="+ex.getMessage()+ " \n");
                }catch (Exception e){
                    e.printStackTrace();
                }
            }

            // 获得定位信息
//            AMapLocation amapLocation = mLocationClient.getLastKnownLocation();
//
//            //如果GPS定位获取不到信号，转成基站定位方式进行定位
//            if (amapLocation == null) {
//                // 设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
//                mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//                // 获取一次定位结果：
//                // 该方法默认为false。
//                mLocationOption.setOnceLocation(false);
//                // 获取最近3s内精度最高的一次定位结果：
//                // 设置setOnceLocationLatest(boolean b)接口为true，启动定位时SDK会返回最近3s内精度最高的一次定位结果。如果设置其为true，setOnceLocation(boolean b)接口也会被设置为true，反之不会，默认为false。
//                mLocationOption.setOnceLocationLatest(false);
//
//                amapLocation = mLocationClient.getLastKnownLocation();
//            }
//            // 上传定位信息
//            if (amapLocation != null) {
//                updateLocation(amapLocation, context);
//            }
//            //停止定位
//            try {
//                mLocationClient.stopLocation();
//            } catch (Exception ex) {
//                logger.info("mLocationClient.stopLocation() error=" + ex.getMessage());
//            }
        }catch (Exception ex){
            try{
                initData("000error occures in line 144="+ex.getMessage()+ " \n");
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public static boolean is4GAvailable(Context context) {
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null
                && activeNetInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
            TelephonyManager telephonyManager = (TelephonyManager)
                    context.getSystemService(
                            Context.TELEPHONY_SERVICE);
            int networkType = telephonyManager.getNetworkType();
            /** Current network is LTE */
            if (networkType == 13) {
                /**此时的网络是4G的*/
                return true;
            }
        }
        return false;
    }

    public static boolean isWifiConnected(Context context)
    {
        ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetworkInfo = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if(wifiNetworkInfo.isConnected())
        {
            return true ;
        }
        return false ;
    }

    public static Map<String, String> getLocation(final Context context) {

        Map<String, String> resultMap = new HashMap<String, String>();

        if(getStringAttrMul(context,"latLatest")!=null){
            resultMap.put("lat", getStringAttrMul(context,"latLatest"));
            resultMap.put("lon", getStringAttrMul(context,"lonLatest"));
        }else{
            resultMap.put("lat", "");
            resultMap.put("lon", "");
        }
        return resultMap;
    }

    public static Map<String, String> getLocationIndex(final Context context) {

        Map<String, String> resultMap = new HashMap<String, String>();

        if(getStringAttrMul(context,"latLatestIndex")!=null){
            resultMap.put("lat", getStringAttrMul(context,"latLatestIndex"));
            resultMap.put("lon", getStringAttrMul(context,"lonLatestIndex"));
        }else{
            resultMap.put("lat", "");
            resultMap.put("lon", "");
        }
        return resultMap;
    }

    /**
     * 根据两个位置的经纬度，来计算两地的距离（单位为KM）
     * 参数为String类型
     * @param lat1 用户纬度
     * @param lng1 用户经度
     * @param lat2 商家纬度
     * @param lng2 商家经度
     * @return
     */
    public static double getDistance(String lat1Str, String lng1Str, String lat2Str, String lng2Str) {
        Double lat1 = Double.parseDouble(lat1Str);
        Double lng1 = Double.parseDouble(lng1Str);
        Double lat2 = Double.parseDouble(lat2Str);
        Double lng2 = Double.parseDouble(lng2Str);

        double radLat1 = rad(lat1);//纬度转换度数
        double radLat2 = rad(lat2);//纬度转换度数
        double difference = radLat1 - radLat2;
        double mdifference = rad(lng1) - rad(lng2);
        double distance = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(difference / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(mdifference / 2), 2)));
        distance = distance * 6378.137;
        distance = Math.round(distance * 10000) / 10000.0;


        return distance;
    }

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    static Handler netHandler = null;

    /**
     * 收发网络数据的线程
     */
    static Thread netThread = new Thread(){
        @Override
        public void run() {
            Looper.prepare();
            netHandler = new Handler(){
                public void dispatchMessage(Message msg) {
                    Bundle data = msg.getData();
                    switch(msg.what){
                        case 0x1: //发送位置
                            String longitude = data.getString("lonCurrent");
                            String latitude = data.getString("latCurrent");
                            String accuracy = data.getString("accuracy");
                            String message = data.getString("message");
                            upDatePosition(mContext,latitude,longitude,message,accuracy);
                            break;

                    }
                };
            };
            Looper.loop();
        }
    };

    private static void upDatePosition(final Context context,final String latCurrent,final String lonCurrent,final String message,final String accuracy) {
        Logger logger = Logger.getLogger(TAG);
        //logger.info( "amapLocation.getSpeed()"+ amapLocation.getSpeed() + "amapLocation.getSatellites()"+ amapLocation.getSatellites() + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ", " + amapLocation);

        try {
            String text = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ", Longitude = " + latCurrent + ", Latitude = " + lonCurrent ;

            initData(text+message);
        } catch (Exception e) {
            Log.d("locationsssss", "updateLocation initData " + e.getLocalizedMessage());
        }


            SharedPreferences sharedPreferences = context.getSharedPreferences("cookie", Context.MODE_MULTI_PROCESS);
            final String driverUuid = sharedPreferences.getString(Const.KEY_TOKEN, "");

            SharedPreferences sharedPreferencesbillid = context.getSharedPreferences("cookie", Context.MODE_MULTI_PROCESS);
            final String waybillId = sharedPreferencesbillid.getString(Const.waybillId, "");

            SharedPreferences sharedPreferencesfirstLoad = context.getSharedPreferences("driver", Context.MODE_MULTI_PROCESS);
            String firstLoad = sharedPreferencesfirstLoad.getString("firstLoad_"+driverUuid, "0");

            try {
                String text = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ", driverUuid = " + driverUuid + ", waybillId = " + waybillId;
                initData(text);
            } catch (Exception e) {
                Log.d("locationsssss", "updateLocation initData " + e.getLocalizedMessage());
            }

            boolean uploadFlag = true;
            double distancefull = 0.3;
            double distancefullBefore = -1;
            double distance = 0;
            String latLatest = "";
            String lonLatest = "";
            String latLastestBefore = getStringAttrMul(context,"latLatestBefore");
            String lonLatestBefore = getStringAttrMul(context,"lonLatestBefore");
            try{
                if(TextUtils.isEmpty(driverUuid)){
                    return;
                }
                String lat = getStringAttrMul(context,"lat");
                String lon = getStringAttrMul(context,"lon");

                //在这里计算当前点和前一个有效点的距离，如果5秒内距离小于20米 不上传位置
                if(lat!=null && !"".equals(lat) && lon!=null && !"".equals(lon)) {
                    distance = getDistance(lat, lon, latCurrent, lonCurrent);
                    if(distance<=0.04){
                        uploadFlag = false;
                    }else{
                        if(accuracy!=null){
                            try{
                                float accuracyFloat = Float.parseFloat(accuracy);
                                if(accuracyFloat>38){
                                    //说明精度不高，先舍弃这个点
                                    uploadFlag = false;
                                }else{
                                    saveStringAttrMul(context,"lat",latCurrent);
                                    saveStringAttrMul(context,"lon",lonCurrent);
                                }
                            }catch (Exception ex){
                                saveStringAttrMul(context,"lat",latCurrent);
                                saveStringAttrMul(context,"lon",lonCurrent);
                            }
                        }else {
                            saveStringAttrMul(context, "lat", latCurrent);
                            saveStringAttrMul(context, "lon", lonCurrent);
                        }
                    }
                }else {
                    saveStringAttrMul(context,"lat",latCurrent);
                    saveStringAttrMul(context,"lon",lonCurrent);
                }
                //下面计算当前点和前一个点的距离，如果超过180米，这个点也将作废，不上传位置
                latLatest = getStringAttrMul(context,"latLatest");
                lonLatest = getStringAttrMul(context,"lonLatest");
                if(latLatest!=null && !"".equals(latLatest) && lonLatest!=null && !"".equals(lonLatest)) {
                    saveStringAttrMul(context,"latLatestBefore",latLatest);
                    saveStringAttrMul(context,"lonLatestBefore",lonLatest);
                    double distance2 = getDistance(latLatest, lonLatest, latCurrent, lonCurrent);
                    distancefull = distance2;
                    if(distance2>0.17){
                        uploadFlag = false;
                        saveStringAttrMul(context,"offsetFlag",String.valueOf(new Date().getTime()));
                    }
                }

                if(latLastestBefore!=null && !"".equals(latLastestBefore) && lonLatestBefore!=null && !"".equals(lonLatestBefore)) {
                    double distance3 = getDistance(latLastestBefore, lonLatestBefore, latCurrent, lonCurrent);
                    distancefullBefore = distance3;
                }

                saveStringAttrMul(context,"latLatest",latCurrent);
                saveStringAttrMul(context,"lonLatest",lonCurrent);

                saveStringAttrMul(context,"latLatestIndex",latCurrent);
                saveStringAttrMul(context,"lonLatestIndex",lonCurrent);
            }catch (Exception ex){
                try{
                    initData("111error occures in line 263="+ex.getMessage()+ " \n");
                }catch (Exception e){
                    e.printStackTrace();
                }
                ex.printStackTrace();
            }

            if(!"1".equals(firstLoad)){
                uploadFlag = true;
            }
            //如果超过2分钟没有上传位置了，上传一次。
            String lastRealUploadTime = getStringAttr(context,"lastRealUploadTime");
            if(lastRealUploadTime!=null && !"".equals(lastRealUploadTime)){
                float accuracyFloat = 0;
                if(accuracy!=null){
                    try{
                        accuracyFloat = Float.parseFloat(accuracy);
                    }catch (Exception ex){
                    }
                }

                try{
                    if( new Date().getTime() - Long.parseLong(lastRealUploadTime) > 60000 && distance>0.05 && accuracyFloat<45){
                        uploadFlag = true;
                        saveStringAttrMul(context,"lat",latCurrent);
                        saveStringAttrMul(context,"lon",lonCurrent);
                    }

                    if( new Date().getTime() - Long.parseLong(lastRealUploadTime) > 180000 && accuracyFloat<45 ){
                        uploadFlag = true;
                        saveStringAttrMul(context,"lat",latCurrent);
                        saveStringAttrMul(context,"lon",lonCurrent);
                    }

                    if( new Date().getTime() - Long.parseLong(lastRealUploadTime) < 3400 ){
                        uploadFlag = false;
                    }
                    String  offsetFlag = getStringAttrMul(context,"offsetFlag");
                    if(offsetFlag!=null && !"".equals(offsetFlag) && offsetFlag.length()>2){
                        if( new Date().getTime() - Long.parseLong(offsetFlag) > 12000 && accuracyFloat<45){
                            uploadFlag = true;
                            saveStringAttrMul(context,"lat",latCurrent);
                            saveStringAttrMul(context,"lon",lonCurrent);
                        }
                    }
                }catch (Exception ex){
                    try{
                        initData("222error occures in line 281="+ex.getMessage()+ " \n");
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    ex.printStackTrace();
                }
            }else{
                uploadFlag = true;
            }

            //logger.info("updateLocation driverUuid " + driverUuid+"---distancefull="+distancefull+"---distance="+distance+" ---waybillId="+waybillId);
            try{
                initData("cal speed="+distancefull/5*3600+" --driverUuid " + driverUuid+"---distancefull="+distancefull+"---distance="+distance+" ---waybillId="+waybillId+"---uploadFlag="+uploadFlag +"---latLatest="+latLatest +"---lonLatest="+lonLatest);
            }catch (Exception ex){
                try{
                    initData("333error occures in line 281="+ex.getMessage()+ " \n");
                }catch (Exception e){
                    e.printStackTrace();
                }
                ex.printStackTrace();
            }

            //uploadFlag = true;
            if (!TextUtils.isEmpty(driverUuid) && uploadFlag) {
                saveStringAttr(context,"lastRealUploadTime",String.valueOf(new Date().getTime()));
                saveStringAttrMul(context,"offsetFlag","");
                String url = Const.DOMAIN + "driverPosition/addDriverPosition.htm";
                //logger.info("updateLocation url="+url);
                RequestQueue requestQueue = Volley.newRequestQueue(context);
                //saveStringAttr(context,"firstLoad_"+driverUuid,"1");

                SharedPreferences sharedPreferencesFirst = context.getSharedPreferences("driver", Context.MODE_MULTI_PROCESS);
                SharedPreferences.Editor editor = sharedPreferencesFirst.edit();
                editor.putString("firstLoad_"+driverUuid,"1");
                editor.commit();

                StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        Log.d(TAG, "onResponse " + s);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.d(TAG, "onErrorResponse " + volleyError.getMessage());
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("token", driverUuid);
                        map.put("lon", lonCurrent);
                        map.put("lat", latCurrent);
//                        try {
//                            map.put("deviceNo", AppUtil.getDeviceBrand());
//                            map.put("c1", AppUtil.getSystemModel());
//                        }catch (Exception ex){
//                            ex.printStackTrace();
//                        }
                        //Log.d(TAG, "getParams " + map);
                        return map;
                    }
                };

                requestQueue.add(stringRequest);
            }

            String lastUploadTime = getStringAttrMul(context,"lastUploadTime");
            boolean gpsFlag = true;
            if(lastUploadTime!=null && !"".equals(lastUploadTime)){
                try{
                    if( new Date().getTime() - Long.parseLong(lastUploadTime) < 4300 ){
                        gpsFlag = false;
                    }
                }catch (Exception ex){
                    try{
                        initData("444error occures in line 281="+ex.getMessage()+ " \n");
                    }catch (Exception e){
                        ex.printStackTrace();
                    }
                    ex.printStackTrace();
                }
            }
            try{
                initData("ready to gps info distancefullBefore="+distancefullBefore+" \n");

            }catch (Exception e){
                e.printStackTrace();
            }
//((amapLocation!=null && amapLocation.getSpeed()<=9))||distancefull<=0.022
            if (!TextUtils.isEmpty(driverUuid) && distancefull<=0.020
                    && gpsFlag && !TextUtils.isEmpty(waybillId) && !"undefined".equals(waybillId)) {
                //logger.info(Const.DOMAIN + "driverPosition/addDriveLowSpeedPosition.htm");
                saveStringAttrMul(context,"lastUploadTime",String.valueOf(new Date().getTime()));

                String url = Const.DOMAIN + "driverPosition/addDriveLowSpeedPosition.htm";
                RequestQueue requestQueue = Volley.newRequestQueue(context);

                StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        Log.d(TAG, "onResponse " + s);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.d(TAG, "onErrorResponse " + volleyError.getMessage());
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("token", driverUuid);
                        map.put("lon", lonCurrent);
                        map.put("lat", latCurrent);
                        map.put("waybillId", waybillId);
                        Log.d(TAG, "getParams " + map);
                        return map;
                    }
                };

                requestQueue.add(stringRequest);
            }
    }

    private static void updateLocation(final AMapLocation amapLocation, final Context context) {
        Logger logger = Logger.getLogger(TAG);
        //logger.info( "amapLocation.getSpeed()"+ amapLocation.getSpeed() + "amapLocation.getSatellites()"+ amapLocation.getSatellites() + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ", " + amapLocation);

        try {
            String text = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ", Longitude = " + String.valueOf(amapLocation == null ? "null" : amapLocation.getLongitude() + ", Latitude = " + String.valueOf(amapLocation == null ? "null" : amapLocation.getLatitude())) ;
            text+="gps speed="+amapLocation.getSpeed()+ " ==getAccuracy="+amapLocation.getAccuracy()
                    + " ==getGpsAccuracyStatus="+amapLocation.getGpsAccuracyStatus()+ " ==getSatellites="+amapLocation.getSatellites()
                    + " ==getProvider="+amapLocation.getProvider()+ " ==getBearing="+amapLocation.getBearing();
            initData(text);
        } catch (Exception e) {
            Log.d("locationsssss", "updateLocation initData " + e.getLocalizedMessage());
        }


        if (amapLocation != null) {
            SharedPreferences sharedPreferences = context.getSharedPreferences("cookie", Context.MODE_MULTI_PROCESS);
            final String driverUuid = sharedPreferences.getString(Const.KEY_TOKEN, "");

            SharedPreferences sharedPreferencesbillid = context.getSharedPreferences("cookie", Context.MODE_MULTI_PROCESS);
            final String waybillId = sharedPreferencesbillid.getString(Const.waybillId, "");

            SharedPreferences sharedPreferencesfirstLoad = context.getSharedPreferences("driver", Context.MODE_MULTI_PROCESS);
            String firstLoad = sharedPreferencesfirstLoad.getString("firstLoad_"+driverUuid, "0");

            try {
                String text = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ", driverUuid = " + driverUuid + ", waybillId = " + waybillId;
                initData(text);
            } catch (Exception e) {
                Log.d("locationsssss", "updateLocation initData " + e.getLocalizedMessage());
            }

            boolean uploadFlag = true;
            double distancefull = 0.3;
            double distancefullBefore = -1;
            double distance = 0;
            String latLatest = "";
            String lonLatest = "";
            String latLastestBefore = getStringAttrMul(context,"latLatestBefore");
            String lonLatestBefore = getStringAttrMul(context,"lonLatestBefore");
            try{
                if(TextUtils.isEmpty(driverUuid)){
                    return;
                }
                String lat = getStringAttrMul(context,"lat");
                String lon = getStringAttrMul(context,"lon");

                //在这里计算当前点和前一个有效点的距离，如果5秒内距离小于20米 不上传位置
                if(lat!=null && !"".equals(lat) && lon!=null && !"".equals(lon)) {
                    distance = getDistance(lat, lon, String.valueOf(amapLocation.getLatitude()), String.valueOf(amapLocation.getLongitude()));
                    if(distance<=0.04){
                        uploadFlag = false;
                    }else{
                        saveStringAttrMul(context,"lat",String.valueOf(amapLocation.getLatitude()));
                        saveStringAttrMul(context,"lon",String.valueOf(amapLocation.getLongitude()));
                    }
                }else {
                    saveStringAttrMul(context,"lat",String.valueOf(amapLocation.getLatitude()));
                    saveStringAttrMul(context,"lon",String.valueOf(amapLocation.getLongitude()));
                }
                //下面计算当前点和前一个点的距离，如果超过300米，这个点也将作废，不上传位置
                latLatest = getStringAttrMul(context,"latLatest");
                lonLatest = getStringAttrMul(context,"lonLatest");
                if(latLatest!=null && !"".equals(latLatest) && lonLatest!=null && !"".equals(lonLatest)) {
                    saveStringAttrMul(context,"latLatestBefore",latLatest);
                    saveStringAttrMul(context,"lonLatestBefore",lonLatest);
                    double distance2 = getDistance(latLatest, lonLatest, String.valueOf(amapLocation.getLatitude()), String.valueOf(amapLocation.getLongitude()));
                    distancefull = distance2;
                    if(distance2>0.21){
                        uploadFlag = false;
                        saveStringAttrMul(context,"offsetFlag",String.valueOf(new Date().getTime()));
                    }
                }

                if(latLastestBefore!=null && !"".equals(latLastestBefore) && lonLatestBefore!=null && !"".equals(lonLatestBefore)) {
                    double distance3 = getDistance(latLastestBefore, lonLatestBefore, String.valueOf(amapLocation.getLatitude()), String.valueOf(amapLocation.getLongitude()));
                    distancefullBefore = distance3;
                }

                saveStringAttrMul(context,"latLatest",String.valueOf(amapLocation.getLatitude()));
                saveStringAttrMul(context,"lonLatest",String.valueOf(amapLocation.getLongitude()));

                saveStringAttrMul(context,"latLatestIndex",String.valueOf(amapLocation.getLatitude()));
                saveStringAttrMul(context,"lonLatestIndex",String.valueOf(amapLocation.getLongitude()));
            }catch (Exception ex){
                try{
                    initData("111error occures in line 263="+ex.getMessage()+ " \n");
                }catch (Exception e){
                    e.printStackTrace();
                }
                ex.printStackTrace();
            }

            if(!"1".equals(firstLoad)){
                uploadFlag = true;
            }
            //如果超过2分钟没有上传位置了，上传一次。
            String lastRealUploadTime = getStringAttr(context,"lastRealUploadTime");
            if(lastRealUploadTime!=null && !"".equals(lastRealUploadTime)){
                try{
                    if( new Date().getTime() - Long.parseLong(lastRealUploadTime) > 60000 && distance>0.05 ){
                        uploadFlag = true;
                        saveStringAttrMul(context,"lat",String.valueOf(amapLocation.getLatitude()));
                        saveStringAttrMul(context,"lon",String.valueOf(amapLocation.getLongitude()));
                    }

                    if( new Date().getTime() - Long.parseLong(lastRealUploadTime) > 150000  ){
                        uploadFlag = true;
                        saveStringAttrMul(context,"lat",String.valueOf(amapLocation.getLatitude()));
                        saveStringAttrMul(context,"lon",String.valueOf(amapLocation.getLongitude()));
                    }

                    if( new Date().getTime() - Long.parseLong(lastRealUploadTime) < 3400 ){
                        uploadFlag = false;
                    }
                    String  offsetFlag = getStringAttrMul(context,"offsetFlag");
                    if(offsetFlag!=null && !"".equals(offsetFlag) && offsetFlag.length()>2){
                        if( new Date().getTime() - Long.parseLong(offsetFlag) > 18000 ){
                            uploadFlag = true;
                            saveStringAttrMul(context,"lat",String.valueOf(amapLocation.getLatitude()));
                            saveStringAttrMul(context,"lon",String.valueOf(amapLocation.getLongitude()));
                        }
                    }
                }catch (Exception ex){
                    try{
                        initData("222error occures in line 281="+ex.getMessage()+ " \n");
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                    ex.printStackTrace();
                }
            }else{
                uploadFlag = true;
            }

            //logger.info("updateLocation driverUuid " + driverUuid+"---distancefull="+distancefull+"---distance="+distance+" ---waybillId="+waybillId);
            try{
                initData("cal speed="+distancefull/5*3600+" --driverUuid " + driverUuid+"---distancefull="+distancefull+"---distance="+distance+" ---waybillId="+waybillId+"---uploadFlag="+uploadFlag +"---latLatest="+latLatest +"---lonLatest="+lonLatest);
            }catch (Exception ex){
                try{
                    initData("333error occures in line 281="+ex.getMessage()+ " \n");
                }catch (Exception e){
                    e.printStackTrace();
                }
                ex.printStackTrace();
            }
            //uploadFlag = true;
            if (!TextUtils.isEmpty(driverUuid) && uploadFlag) {
                saveStringAttr(context,"lastRealUploadTime",String.valueOf(new Date().getTime()));
                saveStringAttrMul(context,"offsetFlag","");
                String url = Const.DOMAIN + "driverPosition/addDriverPosition.htm";
                //logger.info("updateLocation url="+url);
                RequestQueue requestQueue = Volley.newRequestQueue(context);
                //saveStringAttr(context,"firstLoad_"+driverUuid,"1");

                SharedPreferences sharedPreferencesFirst = context.getSharedPreferences("driver", Context.MODE_MULTI_PROCESS);
                SharedPreferences.Editor editor = sharedPreferencesFirst.edit();
                editor.putString("firstLoad_"+driverUuid,"1");
                editor.commit();

                StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        Log.d(TAG, "onResponse " + s);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.d(TAG, "onErrorResponse " + volleyError.getMessage());
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("token", driverUuid);
                        map.put("lon", String.valueOf(amapLocation.getLongitude()));
                        map.put("lat", String.valueOf(amapLocation.getLatitude()));
                        //Log.d(TAG, "getParams " + map);
                        return map;
                    }
                };

                requestQueue.add(stringRequest);
            }

            String lastUploadTime = getStringAttrMul(context,"lastUploadTime");
            boolean gpsFlag = true;
            if(lastUploadTime!=null && !"".equals(lastUploadTime)){
                try{
                    if( new Date().getTime() - Long.parseLong(lastUploadTime) < 4300 ){
                        gpsFlag = false;
                    }
                }catch (Exception ex){
                    try{
                        initData("444error occures in line 281="+ex.getMessage()+ " \n");
                    }catch (Exception e){
                        ex.printStackTrace();
                    }
                    ex.printStackTrace();
                }
            }
            try{
                initData("ready to gps info distancefullBefore="+distancefullBefore+" \n");

            }catch (Exception e){
                e.printStackTrace();
            }
//((amapLocation!=null && amapLocation.getSpeed()<=9))||distancefull<=0.022
            if (!TextUtils.isEmpty(driverUuid) && distancefullBefore<=0.045
                    && gpsFlag && !TextUtils.isEmpty(waybillId) && !"undefined".equals(waybillId)) {
                //logger.info(Const.DOMAIN + "driverPosition/addDriveLowSpeedPosition.htm");
                saveStringAttrMul(context,"lastUploadTime",String.valueOf(new Date().getTime()));

                String url = Const.DOMAIN + "driverPosition/addDriveLowSpeedPosition.htm";
                RequestQueue requestQueue = Volley.newRequestQueue(context);

                StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        Log.d(TAG, "onResponse " + s);
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError volleyError) {
                        Log.d(TAG, "onErrorResponse " + volleyError.getMessage());
                    }
                }) {
                    @Override
                    protected Map<String, String> getParams() throws AuthFailureError {
                        Map<String, String> map = new HashMap<String, String>();
                        map.put("token", driverUuid);
                        map.put("lon", String.valueOf(amapLocation.getLongitude()));
                        map.put("lat", String.valueOf(amapLocation.getLatitude()));
                        map.put("waybillId", waybillId);
                        Log.d(TAG, "getParams " + map);
                        return map;
                    }
                };

                requestQueue.add(stringRequest);
            }
        }
    }

    public static void  saveStringAttrMul(Context context,String key,String value){
        SharedPreferences sharedPreferences = context.getSharedPreferences("parking",Context.MODE_MULTI_PROCESS);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key,value);
        editor.commit();
    }

    public static String getStringAttrMul(Context context,String key){
        SharedPreferences sharedPreferences = context.getSharedPreferences("parking",Context.MODE_MULTI_PROCESS);
        return sharedPreferences.getString(key,"");
    }

    public static void  saveStringAttr(Context context,String key,String value){
        SharedPreferences sharedPreferences = context.getSharedPreferences("parking",Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key,value);
        editor.commit();
    }

    public static String getStringAttr(Context context,String key){
        SharedPreferences sharedPreferences = context.getSharedPreferences("parking",Context.MODE_PRIVATE);
        return sharedPreferences.getString(key,"");
    }

    private static void initData(String text) {
        String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.shjy.driver/files/Download/";
        String fileName = "";
        try {
            fileName = "log-"+formatDate(new Date())+".txt";
        }catch (Exception ex){
            ex.printStackTrace();
        }

        writeTxtToFile(text, filePath, fileName);
    }

    private static  String formatDate(Date date) throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    // 将字符串写入到文本文件中
    public static void writeTxtToFile(String strcontent, String filePath, String fileName) {
        //生成文件夹之后，再生成文件，不然会出错
        makeFilePath(filePath, fileName);

        String strFilePath = filePath+fileName;
        // 每次写入时，都换行写
        String strContent = strcontent + "\r\n";
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {
                Log.d("TestFile", "Create the file:" + strFilePath);
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            Log.e("TestFile", "Error on write File:" + e);
        }
    }

    // 生成文件
    public static File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    // 生成文件夹
    public static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            Log.i("error:", e+"");
        }
    }




}
